package com.tencent.compose.sample.mainpage.sectionItem.molecule

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import app.cash.molecule.launchMolecule
import app.cash.molecule.RecompositionMode
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch

@Composable
fun MoleculeDependencyTestPanelSafe() {
    var log by remember { mutableStateOf("") }
    val scrollState = rememberScrollState()
    val events = remember { MutableSharedFlow<String>() }

    val scope = rememberCoroutineScope()
    var message by remember { mutableStateOf("Molecule initialized") }

    // 使用 LaunchedEffect 在协程里收集事件
    LaunchedEffect(Unit) {
        events.collect { message = it }
    }

    // Launch Molecule
    val models = remember(scope) {
        scope.launchMolecule(RecompositionMode.ContextClock) {
            message // Molecule 观察 message 的变化
        }
    }

    // 收集 Molecule 输出到 log
    LaunchedEffect(models) {
        models.collect { log += "$it\n" }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
            .verticalScroll(scrollState)
    ) {
        Text(
            text = "Molecule Dependency Test Panel",
            fontSize = 22.sp,
            fontWeight = FontWeight.Bold,
            modifier = Modifier.fillMaxWidth(),
            textAlign = TextAlign.Center
        )

        Spacer(modifier = Modifier.height(16.dp))
        Button(onClick = { scope.launch { events.emit("✅ Molecule works!") } }) {
            Text("Test Molecule")
        }

        Spacer(modifier = Modifier.height(16.dp))
        Text(text = "Log:", fontWeight = FontWeight.Bold)
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(200.dp)
                .background(Color(0xFFEFEFEF))
                .padding(8.dp)
        ) {
            Text(text = log)
        }
    }
}

